package com.godenwater.recv.manager;

import java.io.File;
import java.io.IOException;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.apache.mina.core.session.IoSession;

import com.godenwater.recv.server.all.RtuConfig;
import com.godenwater.recv.server.all.RtuServer;

import cn.gov.mwr.sl651.utils.ByteUtil;

public class DownloadThread implements Runnable {

	private IoSession session;

	public DownloadThread(IoSession _session) {
		this.session = _session;
	}

	/**
	 * 执行下发任务，每隔3秒钟下发一次报文
	 */
	public void run() {

		int i = 0;

		String stcd = (String) session.getAttribute("STCD");

		// 下发所有的报文
		File file = RtuConfig.getBinMessage(stcd);
		// 读取文件内容，然后下发
		List<String> lines;
		try {
			lines = FileUtils.readLines(file, "UTF-8");

			for (String line : lines) {
				i++;
				System.out.println(">>正在向 " + stcd + " 发送升级包，第 " + i + " 包. ");
				byte[] byteMessage = ByteUtil.HexStringToBinary(line);
				if (!session.isClosing()) {
					session.write(byteMessage);
				}

				try {
					Thread.sleep(3000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				session.setAttribute("MSGSEQ", i);
			}

			RtuServer.getInstance().getSessionManager()
					.bindUpgrade(session, stcd, "0", 0);

		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

	}

}
